// pages/chat/chat.js
const app = getApp()

import { newChat, sendMessage, getChatMessages } from '../../utils/chat'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    hasUserInfo: false,

    message: '',
    conversationId: '',

    list: [],

    isCreateConversation: false,

    typingTime: null,
    noviceText: '',

    isGptAnswerMe: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options && options.conversation_id) {
      this.setData({
        conversationId: options.conversation_id,
        isCreateConversation: true
      })
      this.getChatMessages()
    }
  },

  getUserInfo: function () {
    wx.getUserProfile({
      desc: '获取头像昵称',
      success: res => {
        wx.setStorage({ key: 'userInfo', data: res.userInfo })
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,

          isCreateConversation: false,
          list: [],
          message: '',
          conversationId: ''
        })
      }
    })
  },

  newChat() {
    let that = this
    newChat().then((res) => {
      const conversationId = res.data
      that.setData({
        conversationId: conversationId
      })
      wx.hideLoading()
    }, (err) => {
      wx.hideLoading()
    })
  },

  sendMessage() {
    let isGptAnswerMe = this.data.isGptAnswerMe
    if(isGptAnswerMe) {
      return
    }
    isGptAnswerMe = true
    let conversationId = this.data.conversationId
    let message = this.data.message

    let list = this.data.list
    list.push({
      sender: '',
      content: message
    })
    list.push({
      sender: 'gpt',
      content: '',
    })

    this.setData({
      message: '',
      list,
      noviceText: '',
      isGptAnswerMe
    })

    sendMessage({
      conversation_id: conversationId,
      user_message: message
    }).then((res) => {
      let list = this.data.list
      list.splice(list.length - 1, 1, {
        sender: 'gpt',
        content: res.data
      })
      this.setData({
        list
      })

      // 打字机效果实现
      this.textTyping(res.data, 0)
    }, (err) => {
      console.log('err', err)
    })
  },

  
  textTyping(message, s) {
    if (message.length <= s) {
      this.setData({
        isGptAnswerMe: false
      })
      return
    }
    let typingTime = setTimeout(() => {
      this.setData({
        noviceText: this.data.noviceText + message[s]
      })
      this.textTyping(message, s + 1)
      clearTimeout(typingTime)
    }, 1000)
  },

  bindKeyInput(e) {
    this.setData({
      message: e.detail.value
    })
  },

  createConversation() {
    this.setData({
      isCreateConversation: true
    })
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    this.newChat()
  },

  goToHistory() {
    wx.navigateTo({
      url: '../history/history',
    })
  },

  getChatMessages() {
    const conversation_id = this.data.conversationId
    getChatMessages({
      conversation_id
    }).then((res) => {
      this.setData({
        list: res.data
      })
    }, (err) => {
      console.log('err', err)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (wx.getStorageSync('userInfo')) {
      this.setData({
        userInfo: wx.getStorageSync('userInfo'),
        hasUserInfo: true
      })
    } else {
      this.setData({
        userInfo: {},
        hasUserInfo: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})